from matplotlib.font_manager import FontProperties
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np

# 修复字体无法显示的问题
font = FontProperties(fname=r"c:\\windows\\fonts\\msyh.ttc", size=10)
# 随机生成数据
cluster1 = np.random.uniform(0.3, 0.5, (10, 10))
cluster2 = np.random.uniform(0.1, 0.5, (10, 10))
# hstack拼接操作
X = np.hstack((cluster1, cluster2)).T
# 用scipy求解距离
K = range(1, 10)
meandistortions = []
for k in K:
    kmeans = KMeans(n_clusters=k)
    kmeans.fit(X)
    meandistortions.append(sum(np.min(
        cdist(X, kmeans.cluster_centers_,
              'euclidean'), axis=1))/X.shape[0])
plt.plot(K, meandistortions, 'bx-')
plt.xlabel('k')
plt.ylabel(u'平均畸变程度', fontproperties=font)
plt.title(u'用肘部法则来确定最佳的K值', fontproperties=font)
plt.show()
